<template>
    <div class="added">
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="120px"
            class="demo-ruleForm">
            <el-row class="container">
                <el-col :span="12">
                    <el-form-item label="基源名称：" prop="jyName">
                        <el-select v-model="ruleForm.jyName" @change="getjy" value-key="id" placeholder="" style="width:300px">
                            <el-option v-for="item in baselist" :key="item.id" :label="item.name" :value="item">{{ item.name }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="种苗照片：">
                        <el-upload class="upload-poster" action="https://jsonplaceholder.typicode.com/posts/"
                            :show-file-list="false" :on-change="imgPreview" :auto-upload="false">
                            <img v-if="plantImg" :src="plantImg" class="avatar">
                            <i v-else class="el-icon-circle-plus avatar-uploader-icon"></i>
                            <div style="color: #1BC46D;">jpg、png、gif格式，60x60像素，不超过2MB</div>
                        </el-upload>
                    </el-form-item>

                    <el-form-item label="种苗数量：" prop="plantNumber">
                        <el-input placeholder="请输入" v-model="ruleForm.plantNumber" style="width: 200px">
                            <template slot="append">

                                <el-select v-model="ruleForm.units" placeholder="单位" style="width:80px !important">
                                    <el-option v-for="item in unitList" :key="item.id" :label="item.name"
                                        :value="item.name">{{ item.name }}</el-option>
                                </el-select>
                            </template>
                        </el-input>
                        <el-button style="margin-left:10px" @click="gounit">单位管理</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="种苗名称：" prop="plantName">
                        <el-input placeholder="请输入内容" v-model="ruleForm.plantName" style="width:300px"></el-input>
                    </el-form-item>
                    <el-form-item label="种苗来源：" prop="source">
                        <el-select v-model="ruleForm.source" placeholder="" style="width:300px">
                            <el-option v-for="item in sourcelist" :key="item.id" :label="item.name"
                                :value="item.name">{{ item.name }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="种苗企业：" v-if="ruleForm.source == '自购'">
                        <el-select v-model="ruleForm.company" placeholder="" style="width:300px">
                            <el-option v-for="item in supplierlist" :key="item.id" :label="item.supplierName"
                                :value="item.supplierName">{{ item.supplierName }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="种植方式：" prop="way">
                        <!-- <el-input placeholder="请输入内容" v-model="ruleForm.way" style="width:300px">
                            </el-input> -->
                        <el-select v-model="ruleForm.way" placeholder="" style="width:300px">
                            <el-option v-for="item in plantingwway" :key="item.id" :label="item.name"
                                :value="item.name">{{ item.name }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="种植基地：" prop="plantBaseName">
                        <el-select v-model="ruleForm.plantBaseName" @change="getjd" placeholder="" style="width:300px">
                            <el-option v-for="item in subordinateBase" :key="item.id" :label="item.name" :value="item">{{ item.name }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属地块：" prop="soilName">
                            <el-select v-model="ruleForm.soilName" multiple  placeholder="" value-key="id" style="width:300px">
                            <el-option v-for="item in soilList" :key="item.id" :label="item.name" :value="item">{{ item.name }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="种植面积：" prop="plantArea">
                        <el-input placeholder="请输入内容" v-model="ruleForm.plantArea" style="width:200px">
                        </el-input>
                        <span style="margin-left:20px;">亩</span>
                    </el-form-item>


                </el-col>
            </el-row>
            <el-row class="container" style="margin-top:10px;">
                <el-col :span="12">
                    <el-form-item label="种植批次号：" prop="batch">
                        <el-input placeholder="请输入内容" v-model="ruleForm.batch" style="width:300px">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="种植人：" prop="plantUserName">

                        <el-select v-model="ruleForm.plantUserName" @change="getuser" value-key="id" placeholder="">
                            <el-option v-for="item in userAll" :key="item.id" :label="item.name"
                                :value="item">{{ item.name }}</el-option>
                        </el-select>

                        <el-button style="margin-left:10px" @click="gouser">种植人</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="种植时间：" prop="plantTime">
                        <el-date-picker style="width:300px" v-model="ruleForm.plantTime" @change="gettime"
                            value-format="yyyy/MM/dd" type="date" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="预计收获时间：" prop="reapTime">
                        <el-date-picker style="width:300px" v-model="ruleForm.reapTime" @change="gettime"
                            value-format="yyyy/MM/dd" type="date" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item class="footerFixed" label-width="0px">
                <el-button type="warning" @click="submitrule('ruleForm')">提交</el-button>
                <el-button @click="backPage">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { unit_findByList, user_findByAll, basesource_findByAll, supplier_findByAll, base_findByAll, plot_findByAll, plant_save, model_crop_loadbind } from "@/request/api"
import { soil_findByBaseId } from '@/request/breedApi'
export default {
    data() {
        return {
            soilId: '',
            plotlist: [],
            plantingwway: [
                { name: '直播' },
                { name: '间作' },
                { name: '轮作' },
                { name: '套作' },
                { name: '其他' },
            ],
            sourcelist: [
                { name: "自购" },
                { name: '栽培' },
                { name: '野生移栽' }
            ],
            subordinateBase: [

            ],
            supplierlist: '',
            baselist: '',
            userAll: '',
            unitList: [],
            labelPosition: 'right',
            ruleForm: {},
            plantImg: '',
            rules: {
                jyName: [{ required: true, message: '不能为空', trigger: 'change' }],
                // plantBaseName: [{ required: true, message: '不能为空', trigger: 'change' }],
                plantNumber: [{ required: true, message: '不能为空', trigger: 'change' }],
                plantName: [{ required: true, message: '不能为空', trigger: 'change' }],
                source: [{ required: true, message: '不能为空', trigger: 'change' }],
                way: [{ required: true, message: '不能为空', trigger: 'change' }],
                soilName: [{ required: true, message: '不能为空', trigger: 'change' }],
                plantArea: [{ required: true, message: '不能为空', trigger: 'change' }],
                batch: [{ required: true, message: '不能为空', trigger: 'blur' }],
                plantUserName: [{ required: true, message: '不能为空', trigger: 'change' }],
                plantTime: [{ required: true, message: '不能为空', trigger: 'blur' }],
                reapTime: [{ required: true, message: '不能为空', trigger: 'blur' }],
            },
            soilList: []
        }
    },
    mounted() {
        this.init()
        var num = ""
        for (var i = 0; i < 5; i++) {
            num += Math.floor(Math.random() * 10);
        }
        var mydate = new Date()
        var year = mydate.toLocaleDateString()
        var date = year.replace(/\//g, "");
        this.ruleForm.batch = date + num
    },
    methods: {
        gettime() {
            if (this.ruleForm.plantTime != "" && this.ruleForm.reapTime != "") {
                var oDate1 = new Date(this.ruleForm.plantTime)
                var oDate2 = new Date(this.ruleForm.reapTime)
                if (oDate1 > oDate2) {
                    this.$notify({
                        title: '提示',
                        message: '采购时间不得早于生产时间',
                        type: 'info'
                    });
                    this.ruleForm.plantTime = ""
                    this.ruleForm.reapTime = ""
                }
            }
        },
        gounit() {
            this.$router.push({
                path: '/unit'
            })
        },
        gouser() {
            this.$router.push({
                path: '/staffsManagement/addedstaff'
            })
        },
        init() {
            unit_findByList("").then((res) => {
                this.unitList = res.data
            })
            user_findByAll("").then((res) => {
                this.userAll = res.data
            })
            model_crop_loadbind("").then((res) => {
                console.log('root:',res);
                this.baselist = res.data

            })
            // basesource_findByAll("").then((res)=>{
            //     this.baselist = res.data
            // })
            supplier_findByAll("").then((res) => {
                this.supplierlist = res.data
            })

            // base_findByAll("").then((res)=>{
            //     this.subordinateBase = res.data
            // })
            //获取所有基地
            plot_findByAll().then((res) => {
                console.log('res',res);
                this.subordinateBase = res.data
            })
        },
        getjy(ele) {

            this.ruleForm.jyId = ele.id
            this.ruleForm.jyName = ele.name

        },
        getdk(ele) {
            console.log(ele);
            this.ruleForm.soilId = ele.id
            this.ruleForm.soilName = ele.name
        },
        getjd(ele) {
            this.soilId = ''
            this.ruleForm.plantBaseId = ele.id
            this.ruleForm.plantBaseName = ele.name
            soil_findByBaseId(`${ele.id}/2`).then((res) => {
                console.log('jd res',res);
                this.soilList = res
            })
        },
        getuser(ele) {
            this.ruleForm.plantUserId = ele.id
            this.ruleForm.plantUserName = ele.name
        },
        imgPreview(file, fileList) {
            this.plantImg = URL.createObjectURL(file.raw);
            let fileName = file.name;
            let regex = /(.jpg|.gif|.png|.jpeg)$/;
            if (regex.test(fileName.toLowerCase())) {
                this.ruleForm.files = file.raw
                this.ruleForm.plantImg = file.name
            } else {
                this.$message.error('请选择图片文件');
            }
        },
        submitrule(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.ruleForm.units == "" || this.ruleForm.units == undefined) {
                        this.$notify({
                            title: '提示',
                            message: '种苗数量单位不能为空',
                            type: 'info'
                        });
                        return false
                    }
                    this.$confirm('请仔细核对所填信息，提交后不能修改！', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let soilName = ''
                        let soilId = ''
                        this.ruleForm.soilName.forEach((item,i)=>{
                            soilName += item.name+','
                            soilId += item.id+','
                        })
                        soilName = soilName.slice(0,-1)
                        soilId = soilId.slice(0,-1)
                        let formdata = new FormData()
                        for (var a in this.ruleForm) {
                            if( a =='soilName'){
                                continue
                            }
                            if (this.ruleForm[a] == null || this.ruleForm[a] == 'null') {
                                this.ruleForm[a] = '';
                                formdata.append(a, '');
                            } else {
                                formdata.append(a, this.ruleForm[a]);
                            }
                        }
                        formdata.append('soilId',soilId)
                        formdata.append('soilName',soilName)
                        // for (const[key,value] of formdata){
                        //     console.log(key,value);
                        // }
                        plant_save(formdata).then((res) => {
                            this.$notify({
                                title: '操作成功',
                                message: '保存成功',
                                type: 'success'
                            });
                            this.$router.push({
                                path: '/plant'
                            })
                            this.init()
                        })
                    })
                } else {
                    return false
                }
            })
        },
        backPage() {
            this.$router.go(-1)
        }
    }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 180px;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.el-upload--text {
    width: 180px;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 90px;
    /* height: 178px; */
    line-height: 140px;
    text-align: center;
    color: #1BC46D;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style lang="less">
.added {
    .el-input .el-input__inner {
        background-color: #FAFAFA !important;
        border: 1px solid #EEEEEE !important;
    }

    .el-textarea__inner {
        background-color: #FAFAFA !important;
        border: 1px solid #EEEEEE !important;
    }
}
</style>
